/* eslint-disable @typescript-eslint/no-var-requires */
const path = require("path");
const webpack = require("webpack");
// fork-ts-checker-webpack-plugin需要单独安装
const ForkTsCheckerWebpackPlugin = require("fork-ts-checker-webpack-plugin");
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
// const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
const nodeExternals = require('webpack-node-externals');

module.exports = {
    entry: "./src/main",
    target: "node",
    // 置为空即可忽略webpack-node-externals插件
    //   externals: {},
    externals: [
        // 添加需要忽略的模块
        nodeExternals(),
        'vertx',
        'hiredis'
        // 其他模块
    ],
    // ts文件的处理
    module: {
        rules: [
            {
                test: /\.ts?$/,
                use: {
                    loader: "ts-loader",
                    options: { transpileOnly: true }
                },
                exclude: [
                    /node_modules/,
                    /test/,
                    /\.spec\.ts$/,
                ],
            }
        ]
    },
    stats: {
        errorDetails: true,
    },
    // 打包后的文件名称以及位置
    output: {
        filename: "main.js",
        path: path.resolve(__dirname, "distOut")
    },
    optimization: {
        usedExports: false,
    },
    resolve: {
        extensions: ['.js', '.ts', '.json'],
        plugins: [new TsconfigPathsPlugin({ configFile: './tsconfig.json' })],
        // modules: [path.resolve(__dirname, 'node_modules')]
        alias: {
            // 如果有必要，可以为特定模块设置别名
            './binary_parser': path.resolve(__dirname, 'node_modules/_bson@0.4.23@bson/lib/bson/binary_parser'),
            './binary': path.resolve(__dirname, 'node_modules/bson/lib/bson/binary'),
            // 其他模块...
        },
    },
    plugins: [
        // 需要进行忽略的插件
        new webpack.IgnorePlugin({
            checkResource(resource) {
                const lazyImports = [
                    "@nestjs/microservices",
                    "@nestjs/microservices/microservices-module",
                    "@nestjs/websockets/socket-module",
                    "cache-manager",
                    "class-validator",
                    "class-transformer",
                    "class-transformer/storage",
                    'ordered-read-streams'
                ];
                if (!lazyImports.includes(resource)) {
                    return false;
                }
                try {
                    require.resolve(resource, {
                        paths: [process.cwd()]
                    });
                } catch (err) {
                    return true;
                }
                return false;
            }
        }),
        new ForkTsCheckerWebpackPlugin(),
        // new BundleAnalyzerPlugin()
    ]
};